import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class RemoveComments {

	private static final String DIR = "D:\\workspace\\SyncService\\src\\";

	enum ParseState {
		BLOCK_COMMENT, LINE_COMMENT, GENERAL
	}

	public static void main(String[] args) throws IOException {
		File dir = new File(DIR);
		processDir(dir, 0);
	}

	private static void processDir(File dir, int level) throws IOException {
		for(int i = 0; i < level; i ++){
			System.out.print('\t');
		}
		System.out.println(dir.getName());
		File[] files = dir.listFiles();
		for (File f : files) {
			if (f.isDirectory()) {
				processDir(f, level + 1);
			} else if (f.isFile()) {
				processFile(f);
			}
		}
	}

	private static void processFile(File f) throws IOException {
		System.out.println();
		System.out.println("Processing file " + f.getName());
		File tmp = File.createTempFile("tmp", "tmp");
		FileReader fileReader = new FileReader(f);
		try {
			BufferedWriter fileWriter = new BufferedWriter(new FileWriter(tmp));
			try {
				char[] inputBuf = new char[2048];
				int count = 0;
				ParseState state = ParseState.GENERAL;
				char previousCharacter = '\0';
				while ((count = fileReader.read(inputBuf)) != -1) {
					int j = 0;
					int i = 0;
					while (i < count) {
						switch (inputBuf[i]) {
						case '/':
							if(previousCharacter == '*' && state == ParseState.BLOCK_COMMENT && state != ParseState.LINE_COMMENT){
								state = ParseState.GENERAL;
							} else if(previousCharacter == '/' && state == ParseState.GENERAL){
								state = ParseState.LINE_COMMENT;
							}
							break;
						case '*':
							if(state == ParseState.GENERAL && previousCharacter == '/'){
								state = ParseState.BLOCK_COMMENT;
							}
							break;
						case '\n':
							if(state == ParseState.LINE_COMMENT){
								state = ParseState.GENERAL;
							}
						default:
							if(state != ParseState.BLOCK_COMMENT && state != ParseState.LINE_COMMENT){
								if(previousCharacter == '/' || previousCharacter == '*'){
									fileWriter.append(previousCharacter);
									System.out.print(previousCharacter);
								}
								fileWriter.append(inputBuf[i]);
								System.out.print(inputBuf[i]);
							}
							break;
						}
						previousCharacter = inputBuf[i];
						i ++;
					}
				}
			} finally {
				fileWriter.close();
			}
		} finally {
			fileReader.close();
		}
		//tmp.renameTo(f);
	}


}
